'use client';

import { useState, useRef } from 'react';
import { createPortal } from 'react-dom';
import { useTTS } from '@/lib/hooks/useAI';

interface VoiceSelectorProps {
  selectedVoice: string;
  onVoiceChange: (voice: string) => void;
  className?: string;
}

// ElevenLabs preset voice list
const VOICE_OPTIONS = [
  {
    id: '21m00Tcm4TlvDq8ikWAM',
    name: 'Rachel',
    description: 'Warm and friendly (Bilingual)',
    gender: 'female',
    language: 'multilingual'
  },
  {
    id: 'AZnzlk1XvdvUeBnXmlld',
    name: 'Domi',
    description: 'Confident and professional (Bilingual)',
    gender: 'female',
    language: 'multilingual'
  },
  {
    id: 'EXAVITQu4vr4xnSDxMaL',
    name: 'Bella',
    description: 'Young and lively (Bilingual)',
    gender: 'female',
    language: 'multilingual'
  },
  {
    id: 'ErXwobaYiN019PkySvjV',
    name: 'Antoni',
    description: 'Mature and stable (Bilingual)',
    gender: 'male',
    language: 'multilingual'
  },
  {
    id: 'MF3mGyEYCl7XYWbV9V6O',
    name: 'Elli',
    description: 'Gentle and delicate (Bilingual)',
    gender: 'female',
    language: 'multilingual'
  },
  {
    id: 'TxGEqnHWrfWFTfGW9XjX',
    name: 'Josh',
    description: 'Energetic and cheerful (Bilingual)',
    gender: 'male',
    language: 'multilingual'
  },
  {
    id: 'VR6AewLTigWG4xSOukaG',
    name: 'Arnold',
    description: 'Deep and authoritative (Bilingual)',
    gender: 'male',
    language: 'multilingual'
  },
  {
    id: 'pNInz6obpgDQGcFmaJgB',
    name: 'Adam',
    description: 'Clear and professional (Bilingual)',
    gender: 'male',
    language: 'multilingual'
  },
  {
    id: 'yoZ06aMxZJJ28mfd3POQ',
    name: 'Sam',
    description: 'Natural and fluent (Bilingual)',
    gender: 'male',
    language: 'multilingual'
  }
];

export function VoiceSelector({ selectedVoice, onVoiceChange, className = "" }: VoiceSelectorProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [previewingVoice, setPreviewingVoice] = useState<string | null>(null);
  const [buttonRect, setButtonRect] = useState<DOMRect | null>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const { textToSpeech, loading: ttsLoading } = useTTS();

  const selectedVoiceOption = VOICE_OPTIONS.find(v => v.id === selectedVoice) || VOICE_OPTIONS[0];

  const handleToggle = () => {
    if (!isOpen && buttonRef.current) {
      const rect = buttonRef.current.getBoundingClientRect();
      setButtonRect(rect);
    }
    setIsOpen(!isOpen);
  };

  const handlePreview = async (voiceId: string) => {
    if (previewingVoice === voiceId) return;
    
    try {
      setPreviewingVoice(voiceId);
      const result = await textToSpeech({
        text: 'Hello, this is a voice preview.',
        voice: voiceId,
        format: 'mp3',
        language: localStorage.getItem('preferredLanguage') || 'en'
      });
      
      const audio = new Audio(result.audioUrl);
      audio.onended = () => setPreviewingVoice(null);
      audio.onerror = () => setPreviewingVoice(null);
      await audio.play();
    } catch (error) {
      console.error('Voice preview failed:', error);
      setPreviewingVoice(null);
    }
  };

  const dropdownContent = isOpen && buttonRect && (
    <div className="fixed inset-0 z-[9999]">
      {/* Background */}
      <div
        className="absolute inset-0 bg-transparent"
        onClick={() => setIsOpen(false)}
      />
      
      {/* Dropdown menu */}
      <div
        className="absolute bg-white border border-gray-200 rounded-xl shadow-xl max-h-80 overflow-y-auto"
        style={{
          top: buttonRect.bottom + 8,
          left: buttonRect.left,
          width: buttonRect.width,
          minWidth: '320px'
        }}
      >
        {VOICE_OPTIONS.map((voice) => (
          <div
            key={voice.id}
            className={`flex items-center gap-3 px-4 py-3 hover:bg-gray-50 cursor-pointer transition-colors ${
              selectedVoice === voice.id ? 'bg-blue-50' : ''
            }`}
            onClick={() => {
              onVoiceChange(voice.id);
              setIsOpen(false);
            }}
          >
            <div className="w-10 h-10 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-sm">
              <span className="text-sm font-semibold text-white">
                {voice.gender === 'male' ? '♂' : '♀'}
              </span>
            </div>
            <div className="flex-1 min-w-0">
              <div className="font-semibold text-gray-900">{voice.name}</div>
              <div className="text-sm text-gray-500">{voice.description}</div>
            </div>
            <button
              onClick={(e) => {
                e.stopPropagation();
                handlePreview(voice.id);
              }}
              disabled={ttsLoading || previewingVoice === voice.id}
              className="p-2 text-gray-400 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors disabled:opacity-50"
              title="Preview voice"
            >
              {previewingVoice === voice.id ? (
                <div className="w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full animate-spin" />
              ) : (
                <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M9.383 3.076A1 1 0 0110 4v12a1 1 0 01-1.617.792L4.617 13H2a1 1 0 01-1-1V8a1 1 0 011-1h2.617l3.766-3.792a1 1 0 011.617.792zM14.657 2.929a1 1 0 011.414 0A9.972 9.972 0 0119 10a9.972 9.972 0 01-2.929 7.071 1 1 0 01-1.414-1.414A7.971 7.971 0 0017 10c0-2.21-.894-4.208-2.343-5.657a1 1 0 010-1.414zm-2.829 2.828a1 1 0 011.415 0A5.983 5.983 0 0115 10a5.984 5.984 0 01-1.757 4.243 1 1 0 01-1.415-1.415A3.984 3.984 0 0013 10a3.983 3.983 0 00-1.172-2.828 1 1 0 010-1.415z" clipRule="evenodd" />
                </svg>
              )}
            </button>
          </div>
        ))}
      </div>
    </div>
  );

  return (
    <>
      <div className={`relative ${className}`}>
        {/* Currently selected voice */}
        <button
          ref={buttonRef}
          onClick={handleToggle}
          className="flex items-center gap-3 px-4 py-3 text-sm bg-white border border-gray-200 rounded-xl hover:bg-gray-50 transition-all duration-200 shadow-sm"
        >
          <div className="w-8 h-8 bg-gradient-to-br from-blue-500 to-purple-600 rounded-xl flex items-center justify-center shadow-sm">
            <span className="text-sm font-semibold text-white">
              {selectedVoiceOption.gender === 'male' ? '♂' : '♀'}
            </span>
          </div>
          <div className="text-left flex-1">
            <div className="font-semibold text-gray-900">{selectedVoiceOption.name}</div>
            <div className="text-sm text-gray-500">{selectedVoiceOption.description}</div>
          </div>
          <svg className={`w-5 h-5 text-gray-400 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
          </svg>
        </button>
      </div>

      {/* Portal rendered dropdown menu */}
      {typeof window !== 'undefined' && dropdownContent && createPortal(dropdownContent, document.body)}
    </>
  );
}